package com.ibm.mongo;

import org.bson.BSONObject;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.interfaces.IResultCursor;
import com.ibm.util.JSONUtility;
import com.mongodb.DBCursor;

/** 
 * @author Yaoliang Chen
 * @version May 27, 2014 
 * Description
 */

public class MongoResultCursor implements IResultCursor<ObjectNode> {

	
	private DBCursor _cursor;
	private String keyTag;
	
	public MongoResultCursor(DBCursor cursor, String tagName){
		_cursor = cursor;
		keyTag = tagName;
	}

	public boolean hasNext() {
		if(_cursor == null)
			return false;
		return _cursor.hasNext();
	}

	public ObjectNode next() {
		BSONObject o = _cursor.next();
		if(o.containsField("_id"))
			o.put(keyTag, o.removeField("_id"));
		return (ObjectNode) JSONUtility.newJSONNode(o.toMap());
	}

	public void close() {
		if(_cursor != null)
			_cursor.close();
	}

	public int count() {
		if(_cursor != null)
			return _cursor.count();
		return 0;
	}

	public IResultCursor<ObjectNode> batchSize(int n) {
		if(_cursor != null)
			return new MongoResultCursor(_cursor.batchSize(n), keyTag);
		return new MongoResultCursor(null, keyTag);
	}

	public IResultCursor<ObjectNode> skip(int n) {
		if(_cursor != null)
			return new MongoResultCursor(_cursor.skip(n), keyTag);
		return new MongoResultCursor(null, keyTag);
	}

}
